<template>
    <div class="comment-detail-container">
        <el-tabs v-model="activeTabName">
            <el-tab-pane label="STORY" name="story">
                <div v-if="campaign" v-html="campaign.campaignStory" class="story-area">

                </div>
            </el-tab-pane>
            <!--暂时隐藏-->
            <el-tab-pane v-if="!preview" name="update">
                <div slot="label">
                    <span>UPDATES</span>
                    <div style="float: right;font-weight:bold;margin-left:6px;">
                        {{updateTotalSize}}
                    </div>
                </div>

                <!--增加新的update-->
                <div class="update-area" v-if="campaign.ownerId == userId">

                    <el-input type="text" v-model="title" class="title" placeholder="title"></el-input>

                    <el-input type="textarea" v-model="updateContent" placeholder="content"
                              :autosize="{minRows:3}"></el-input>

                    <el-button type="primary" class="submit-button" @click="addNewUpdate">SUBMIT</el-button>
                </div>
                <update-info-item v-for="(item, index) in updateList" :updateItem="item"
                                  :ownerId="campaign.ownerId" :campaignId="campaign.id"></update-info-item>
            </el-tab-pane>
            <el-tab-pane v-if="!preview" name="comment">

                <div slot="label">
                    <span>COMMENTS</span>
                    <div style="float: right;font-weight:bold;margin-left:6px;">
                        {{commentTotalSize}}
                    </div>
                </div>

                <!--改动层级结构需要调整评论回复组件的parent属性-->

                <div class="comment-area" v-if="isBacker">

                    <!--增加新的评论-->
                    <el-input type="textarea" v-model="commentContent" :autosize="{minRows:3}"></el-input>

                    <el-button type="primary" class="submit-button" @click="addNewComment">SUBMIT</el-button>
                </div>

                <div v-else class="comment-tip-area">
                    <div type="info">
                        <p>You must be a backer to comment.</p>
                    </div>
                </div>


                <comment-item v-for="(item, index) in commentList" :commentItem="item"
                              :ownerId="campaign.ownerId" :campaignId="campaign.id"
                              @addCommentHandler="addCommentCallback"
                              :canReply="isBacker"
                              :listIndex="index"
                ></comment-item>
            </el-tab-pane>

            <el-tab-pane v-if="!preview" name="backer">

                <div slot="label">
                    <span>BACKERS</span>
                    <div style="float: right;font-weight:bold;margin-left:6px;">
                        {{backerTotalSize}}
                    </div>
                </div>

                <!--改动层级结构需要调整评论回复组件的parent属性-->

                <div class="backer-area">
                    <backer-item v-for="(item, index) in backerList" :backerItem="item"
                                 :ownerId="campaign.ownerId" :campaignId="campaign.id"></backer-item>

                    <el-button size="small" type="primary" v-if="backerTotalSize > currentBackerPosition"
                               @click="loadMoreBacker">Load More
                    </el-button>

                </div>

            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
    import UpdateInfoItem from "./UpdateInfoItem"
    import CommentItem from "./CommentItem"
    import BackerItem from "./BackerItem"
    import {mapState, mapMutations} from 'vuex'
    import {saveComment} from "@/api/comment";
    import {apiSaveCampaignUpdate} from "@/api/update";
    import {apiQueryUpdateByCID} from "@/api/update";
    import {apiQueryUserPeakByCID} from '@/api/user_peak'
    import {saveUserLog} from '@/api/log'

    export default {
        props: {
            campaign: {},
            campaignLoadStatus: {},
            preview: {
                default: false
            },
            isBacker: {
                default: false
            },
        },
        components: {
            UpdateInfoItem,
            CommentItem,
            BackerItem
        },
        data() {
            return {
                activeTabName: 'story',
                commentContent: '',
                updateContent: '',
                title: '',
                updateList: [],
                backerList: [],
                commentList: [],
                updateTotalSize: 0,
                backerTotalSize: 0,
                commentTotalSize: 0,
                currentBackerPosition: 5,
                backerPageId: 1
            }
        },
        computed: {
            ...mapState({
                'userId': state => state.user.userId,
                'userName': state => state.user.name,
            }),
        },
        watch: {
            campaignLoadStatus(newValue, oldValue) {
                var that = this
                if (true == newValue) {
                    apiQueryUpdateByCID(this.campaign.id).then((res) => {
                        that.updateList = res.data.records
                        that.updateTotalSize = res.data.total
                    }).catch((error) => {
                        console.log(error)
                    })
                    setTimeout(function () {
                        that.replaceHtml()
                    }, 2000)
                    that.initLoad()
                }
            },
            activeTabName: function (val, oldVal) { //监听切换状态

                if ("comment" == val) {
                    var tip = {
                        operation: "Check comoments",
                        params: JSON.stringify({"userId": this.userId, "campaignId": this.campaign.id})

                    }
                } else if ("update" == val) {
                    var tip = {
                        operation: "Check updates",
                        params: JSON.stringify({"userId": this.userId, "campaignId": this.campaign.id})

                    }
                } else if ("backer" == val) {
                    var tip = {
                        operation: "Check backers",
                        params: JSON.stringify({"userId": this.userId, "campaignId": this.campaign.id})
                    }
                }

                saveUserLog(tip);


            }
        },
        mounted() {
        },

        methods: {
            addCommentCallback(newReply, listIndex) {
                console.log("888")
                // 添加评论的回调
                this.commentList[listIndex].replyList = this.commentList[listIndex].replyList || []
                this.commentList[listIndex].replyList.push(newReply)
            },
            loadMoreBacker() {
                // this.$emit("loadMoreBackerCallback")

                var tip = {
                    operation: "Load more backers",
                    params: JSON.stringify({"userId": this.userId, "campaignId": this.campaign.id})
                }

                saveUserLog(tip);


                this.backerPageId++
                this.loadBackerByPage(this.backerPageId)
            },
            replaceHtml() {
                this.handleImage()
            },
            handleImage() {
                $(".story-area img").each(function (index, element) {
                    var imageUrl = $(element).attr("data-src") || ""
                    if ("" != imageUrl) {
                        $(element).attr("src", imageUrl)
                    }

                })
            },
            loadBackerByPage(pageId, pageSize = 15) {
                var that = this
                console.error("9999999999")
                apiQueryUserPeakByCID(this.campaign.id, pageId, pageSize).then((res) => {
                    console.error("9999999999")
                    var finalUpadtaeList = res.data.records || []
                    $.each(finalUpadtaeList, function (index, item) {
                        that.backerList.push(item)
                    })
                    that.backerTotalSize = res.data.total || 0
                }).catch((err) => {
                    console.log(err)
                })
            },
            initLoad() {

                this.loadBackerByPage(1)

                this.$store.dispatch('listCommentsByCID', this.campaign.id).then((res) => {

                    if (0 === res.code) {
                        // 如果查询成功
                        this.commentList = res.comment.records
                        this.commentTotalSize = res.comment.total
                    }


                }).catch((err) => {
                    console.log(err)
                })

            },
            // 增加新的评论
            addNewComment() {

                var tempInput = this.commentContent || ""
                if ("" == tempInput) {

                    this.$message.error("content can't be empty")
                    return

                }

                var that = this
                var newComment = {
                    userId: this.userId,
                    campaignId: this.campaign.id,
                    content: this.commentContent,
                    userName: this.userName
                }

                var tip = {
                    operation: "Submit comments",
                    params: JSON.stringify({"userId": this.userId, "campaignId": this.campaign.id})

                }

                saveUserLog(tip);


                saveComment(newComment).then((res) => {
                    newComment.id = res.commentId
                    that.commentList = that.commentList || []
                    that.commentList.push(newComment)
                    that.commentContent = ""
                    that.$message.success("success")
                })
            },

            // 增加新的更新
            addNewUpdate() {
                var that = this
                var newUpdate = {
                    userId: this.userId,
                    campaignId: this.campaign.id,
                    content: this.updateContent,
                    title: this.title
                }
                apiSaveCampaignUpdate(newUpdate).then((res) => {
                    newUpdate.id = res.updateId
                    that.updateList = that.updateList || []
                    that.updateList.push(newUpdate)
                    that.updateContent = ""
                    that.$message.success("success")
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    .comment-detail-container {
        width: 100%;
        .story-area{
            font-size: 16px;
            line-height: 24px;
        }
        .comment-area {
            margin-top: 26px;
            text-align: center;
             font-size: 16px;
            line-height: 24px;
            .submit-button {
                margin: 16px;
            }
        }

        .comment-tip-area {
            margin: 30px 0px;
            text-align: center;
            border: 1px solid rgb(200, 200, 200);
            width: 100%;
            p {
                font-size: 22px;
                padding: 0 10%;
                margin: 13px 0;
                color: rgb(200, 200, 200);
            }
        }

        .update-area {
            text-align: center;
             font-size: 16px;
            line-height: 24px;
            .title {
                margin: 16px 0;
            }
            .submit-button {
                margin: 26px;
            }
        }
        .backer-area {
            text-align: center;
        }
    }

</style>